<template>
  <div style="display: flex; height: 100vh;">
    <!-- 左边PDF预览 -->
    <div style="flex: 2; border-right: 1px solid #ddd;">
      <iframe
          v-if="pdfUrl"
          :src="pdfUrl"
          width="100%"
          height="100%"
          frameborder="0"
      ></iframe>
      <div v-else style="text-align: center; margin-top: 20px;">请选择一个PDF进行预览</div>
    </div>

    <!-- 右边上传区域 -->
    <div style="flex: 1; padding: 20px;">
      <h2>上传PDF</h2>
      <el-upload
          action="http://localhost:2626/file/upload"
          :data="{ uid: form.pdf_uid }"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :before-upload="beforeUpload"
      >
        <el-button type="primary">选择并上传PDF</el-button>
      </el-upload>

      <div v-if="uploadedUrl" style="margin-top: 20px;">
        <el-form :model="form">
          <el-form-item label="PDF名称">
            <el-input v-model="form.pdf_name" disabled></el-input>
          </el-form-item>
          <el-form-item label="上传用户ID">
            <el-input v-model="form.pdf_uid"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submitToDatabase">提交到数据库</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      pdfUrl: '',         // 预览用的链接
      uploadedUrl: '',    // 上传后返回的url
      form: {
        pdf_name: '',
        pdf_uid: 1,
        pdf_parent_folder_name: '',
        pdf_url: '',
        pdf_upload_time: '' // 可选
      }
    };
  },
  methods: {
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      if (!isPDF) {
        this.$message.error('只能上传PDF文件！');
      }
      return isPDF;
    },
    handleUploadSuccess(response) {
      console.log(response.code)
      console.log(response.msg)
      console.log(response.data)
        this.uploadedUrl = response.data;  // 后端返回的url
        this.pdfUrl = response.data;        // 用于预览

        // 自动填充表单部分字段
        const parts = this.uploadedUrl.split('/');
        const parentFolderName = parts[parts.length - 2];
        const fileName = parts[parts.length - 1];

        this.form.pdf_name = fileName;
        this.form.pdf_parent_folder_name = parentFolderName;
        this.form.pdf_url = this.uploadedUrl;
    },
    submitToDatabase() {
      if (!this.form.pdf_uid) {
        this.$message.warning('请填写用户ID');
        return;
      }

      axios.post('http://localhost:2626/pdf/add', this.form)
          .then(res => {
            if (res.data.code === 200) {
              this.$message.success('录入成功！');
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(err => {
            this.$message.error('录入失败');
          });
    }
  }
}
</script>

<style scoped>
h2 {
  margin-bottom: 20px;
}
</style>
